package com.lu.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.lu.common.core.exception.CaptchaException;
import com.lu.common.core.utils.StringUtils;
import com.lu.common.core.web.domain.AjaxResult;
import com.lu.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @program LuCloud-RuoYi
 * @description: 验证码过滤器
 * @author: zhanglu
 * @create: 2020-07-01 19:48:00
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {

    private final static String AUTH_URL = "/oauth/token";

    @Autowired
    private ValidateCodeService validateCodeService;

    private static final String BASIC = "Basic ";

    private static final String CODE = "code";

    private static final String UUID = "uuid";

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            //非登陆请求，不处理
            if(!StringUtils.containsIgnoreCase(request.getURI().getPath(), AUTH_URL)){
                return chain.filter(exchange);
            }
            //消息头存在内容，且不存在验证码参数，不处理
            String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
            if(StringUtils.isNotEmpty(header) && StringUtils.startsWith(header, BASIC)
                && !request.getQueryParams().containsKey(CODE)
                && !request.getQueryParams().containsKey(UUID)){
                return chain.filter(exchange);
            }
            try {
                validateCodeService.checkCapcha(request.getQueryParams().getFirst(CODE),
                        request.getQueryParams().getFirst(UUID));
            } catch (CaptchaException e) {
                ServerHttpResponse response = exchange.getResponse();
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(AjaxResult.error(e.getMessage()))))
                );
            }
            return chain.filter(exchange);
        };
    }

}
